const {exec}=require("../db")

function addData(){

}
class Cart{
    async add(req,res){
        let {gid,gname,gprice,uid,gurl,number}=req.body;
        let sql=`INSERT INTO cart (gid,name,price,number,points,subtotal,url,uid) VALUES (?,?,?,?,?,?,?,?)`;
        let params=[gid,gname,gprice,number,gprice,gprice,gurl,uid];
        try {
            let isAdd=await exec('SELECT * FROM cart WHERE uid=? and gid=?',[uid,gid]);
            if(isAdd.length==0){
                let results=await exec(sql,params);
                if(results.affectedRows>=1){
                    res.json({msg:'添加成功',code:200})
                }else {
                    res.json({msg:'添加失败',code:404})
                }
            }else {
                let sql=`UPDATE cart set number=?,subtotal=number*price WHERE cid=?`
                let results=await exec(sql,[isAdd[0].number+1,isAdd[0].cid]);
                if(results.affectedRows>=1){
                    res.json({msg:'成功',code:200})
                }else {
                    res.json({msg:'失败',code:404})
                }
            }
        } catch (error) {
            res.json({msg:'数据出错',code:300})
        }
    }
    async del(req,res){
        let {cid}=req.query;
        let sql=`DELETE FROM cart WHERE cid=?`;
        let params=[cid];
        try {
            let results=await exec(sql,params);
            if(results.affectedRows>=1){
                res.json({msg:'删除成功',code:200})
            }else {
                res.json({msg:'删除失败',code:404})
            }
        } catch (error) {
            res.json({msg:'服务器错误',code:300})
        }
    }
    async all(req,res){
        let {uid}=req.query;
        let sql=`SELECT * FROM cart WHERE uid=?`;
        try {
            let results=await exec(sql,[uid]);
            if(results.length>=1){
                res.json({msg:'成功',list:results,code:200})
            }else {
                res.json({msg:'失败',code:404})
            }
        } catch (error) {
            res.json({msg:'服务器错误',code:300})
        }
    }

    async count(req,res){
        let {uid}=req.query;
        let sql=`SELECT COUNT(*) as num FROM cart WHERE uid=?`;
        try {
            let results=await exec(sql,[uid]);
            if(results.length>=1){
                res.json({msg:'成功',num:results[0].num,code:200})
            }else {
                res.json({msg:'失败',code:404})
            }
        } catch (error) {
            res.json({msg:'服务器错误',code:300})
        }
    }
    async updata(req,res){
        let {cid,number}=req.query;
        try {
            let sql=`UPDATE cart set number=?,subtotal=number*price WHERE cid=?`
            let results=await exec(sql,[number,cid]);
            if(results.affectedRows>=1){
                res.json({msg:'成功',code:200})
            }else {
                res.json({msg:'失败',code:404})
            }
        } catch (error) {
            res.json({msg:'服务器错误',code:300})
        }
    }
}

module.exports=new Cart;